<template>
  <div class="addDiscussContainer responseContainer autoGrow flex-column">
    <div class="sub-title">
      <el-button @click="openCreateDialog({account:service})" type="primary" size="small" icon="el-icon-plus">创建</el-button>
    </div>
    <div class="autoGrow flex-row">
      <div class="chooseAccount flex-column choose-account">
        <div class="autoGrow">
          <div class="choose-account-list">
              <label :class="['flex-row', 'account-item',service.wxid === item.wxid?'checked':'']" v-for="(item) in accounts" :key="item.id" @click="serviceChange(item)">
                <friend
                    :avatar="item.avatar"
                    :name="item.name"
                    :wxid="item.wxid"
                    :gender="item.gender"
                    class="account-item-friend"
                />
              </label> 
          </div>
        </div>
          <!-- <div class="tips operateTip">
            <p>注：</p>
            <p>主动添加好友：通过搜索或扫码，添加名片等方式主动添加对方为好友</p>
            <p>被动添加好友：对方通过搜索或扫码，添加名片等方式添加客服账号为好友</p>
          </div> -->
        <!-- </choose-service-account> -->
      </div>
      <!-- <div class="addDiscussMember flex-column">
        <div class="subTitle">好友添加方式</div>
        <layui-select placeholder="全部类型" :options="selectOptions" @selectChange="selectChange"></layui-select>
      </div> -->
      <div v-loading="progressListLoading" class="discuss-detail-container autoGrow flex-column">
        <div v-if="0">
          <div class="subTitle">应答内容</div>
          <el-divider></el-divider>
          <messageButtonGroup
            :csid="csid"
            :wxid="service.wxid" 
            @create="createMessage"
          />
          <el-divider v-if="messages.length"></el-divider>
          <div class="quick-plane">
            <div class="quick-item" v-for="(reply, index) in messages" :key="index">
              <div class="quick-item-createtime" style="text-align:right">
                  <i @click.stop="messages.splice(index,1)" class="el-icon-close quick-item-close"></i>
              </div>
              <messageCard :message="reply" />
            </div>
          </div> 
          <el-divider></el-divider>
          <div class="sendButtons">
            <button class="layui-btn layui-btn-sm" @click="createResponse">创建</button>
          </div>
          <el-divider></el-divider>
        </div>
        
        <div class="autoGrow flex-column detailList">
          <div class="autoGrow flex-column" style="justify-content: center;align-items: center;" v-if="progressList.length === 0">
            <i style="font-size:64px;color:#ccc" class="el-icon-warning"></i>
            <div class="fontGrey" style="margin-top:20px">列表暂无数据</div>
            <el-button style="margin-top:20px" @click="openCreateDialog({account:service})" size="small" icon="el-icon-plus">创建</el-button>
          </div>
          <div class="ongoing-item flex-row"
            :key="index"
            v-for="(progress, index) in progressList"
            @click="toggleDetailShow(progress, index)"
            >
            <div class="flex-row progress-head">
              <img :src="progress.service.avatar" class="service-avatar" alt="">
              <div class="flex-column autoGrow service-info">
                <div class="textEllipsis">{{progress.service.name}}</div>
                <div class="progress-detail-info fontGrey">
                  {{ ['全部','主动','被动'][progress.addtype] }}添加好友方式
                </div>
              </div>
            </div>
            <div class="fontGrey progress-detail-setting flex-column">
              <span>设置了 {{ progress.messages.length }} 条消息 </span> 
              <span style="margin-top:10px">已回复 {{ progress.responseRecordList.length }} 次</span>
            </div>
            <div class="fontGrey progress-detail-time">
              {{ formatTime(progress.createdate||new Date()) }}   
            </div>
             
          </div>
        </div>
      </div>
    </div>

    <el-drawer
      :visible.sync="detailDrawer"
      custom-class="detail-drawer"
      direction="rtl"
      size="600px"
       >
        <div slot="title" class="detail-drawer-title">
          <span>详情</span>

          <div class="detail-drawer-button-group">
            <el-tooltip class="item" effect="dark" content="编辑" placement="bottom">
              <el-button @click="openEditDialog(progress)" size="medium" type="text" icon="el-icon-edit"></el-button>
            </el-tooltip>
            <!-- <button class="layui-btn layui-btn-xs layui-btn-danger dismissGroup" @click="deleteSetting(progress)">删除</button> -->

            <el-tooltip class="item" effect="dark" content="删除" placement="bottom">
              <el-button @click="deleteSetting(progress)" size="medium" type="text" icon="el-icon-delete"></el-button>
            </el-tooltip>
            
          </div>
          
        </div>
        <div class="detail-drawer-container">

          <el-divider content-position="left">账号</el-divider>
          <friend
            v-if="progress.service"
            :name="progress.service.name"
            :avatar="progress.service.avatar"
            :gender="progress.service.gender"
            :wxid="progress.service.wxid"
            class="record-user-friend"   
          />
          <el-divider content-position="left">添加方式</el-divider>
          <span>{{ ['全部','主动','被动'][progress.addtype] }}添加好友方式</span>
          <el-divider content-position="left">回复内容</el-divider>
          <div class="quick-item" v-for="(reply, index) in progress.messages" :key="index">
            <messageCard :message="reply" />
          </div>
          <el-divider content-position="left">回复记录</el-divider>
          <div class="flex-row record-user-item" v-for="(item) in progress.responseRecordList" :key="item.id">
            <friend
              :name="item.nickname"
              :avatar="item.avatar"
              :wxid="item.wxid"
              class="record-user-friend"   
            />
            <div class="fontGrey">{{ formatTime(item.createtime) }}</div>
          </div>
          <div v-if="progress.responseRecordList&&progress.responseRecordList.length === 0">
            暂无应答记录
          </div>
        
        </div> 
    </el-drawer>  

    <el-dialog @closed="createDialogClosed" :title="createDialogId?'编辑':'创建'" :close-on-click-modal="false" :visible.sync="createDialog" width="600px">
      <div class="create-container">

        <div class="create-item">
          <span class="create-item-title">应答账号</span>
          <div class="create-item-content">
            <el-select :disabled="!!createDialogId" :filterable="true" :filter-method="e=>createFilterKeyword=e" @change="createAccountChange" :value="createDialogAccount.name" placeholder="请选择应答账号">
              <el-option
                v-for="item in createFilterAccounts"
                :key="item.id"
                :value="item.id"
                class="create-item-account"
                >

                <img class="create-item-account-avatar" :src="item.avatar" />
                <span>{{item.name}}</span>

              </el-option>
            </el-select>
          </div>
          <div></div>
        </div>
        <div class="create-item">
          <span class="create-item-title">应答类型</span>
          <div class="create-item-content">
            <el-select v-model="sendType" placeholder="请选择">
              <el-option
                v-for="item in selectOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value">
                
              </el-option>
            </el-select>
          </div>
          <div></div>
        </div>
        <div class="create-item">
          <span class="create-item-title">应答消息</span>
          <div class="create-item-content">
              <messageButtonGroup
                :csid="csid"
                :wxid="service.wxid" 
                @create="createMessage"
              />
          </div>
          <div></div>
        </div>
        <div class="create-item">
          <span class="create-item-title"></span>
          <div class="create-item-content">
            <div class="quick-plane">
                <div class="quick-item" v-for="(reply, index) in messages" :key="index">
                  <div class="quick-item-createtime" style="text-align:right">
                      <i @click.stop="messages.splice(index,1)" class="el-icon-close quick-item-close"></i>
                  </div>
                  <messageCard :message="reply" />
                </div>
              </div> 
          </div>
        </div>
        
      </div>
      <div class="create-ctrl">
        <el-button v-if="createDialogId" :loading="createSubmitLoading" type="primary" @click="updateResponse">修改</el-button>
        <el-button v-else :loading="createSubmitLoading" type="primary" @click="createResponse">提交</el-button>
        <el-button @click="createDialog=false">取消</el-button>
      </div>
      
    </el-dialog>

  </div>
</template>
<script>
import ChooseServiceAccount from '@/components/chooseServiceAccount';
import UserListItem from '@/components/userListItem';
import QuickReplies from './quickReplies';
import messageButtonGroup from '@/components/message-button-group'
import messageCard from '@/components/message-card'
import LayuiSelect from '@/components/layuiSelect';
import Friend from '@/components/friend'
import message from '@/components/message'
import { mapState } from 'vuex';
import pinyin from '@/lib/pinyin'

export default {
  name: 'addDiscuss',
  data() {
    return {
      service: {},
      
      
      progressList: [],
      progressListLoading:false,
      progress:{},
      choosenMessage: null,
      

      detailDrawer:false,
      // 创建编辑框
      createSubmitLoading:false,
      createDialog:false,
      createDialogId:0,
      createFilterKeyword:'',
      createDialogAccount:{},
      sendType: 0,
      selectOptions: [
        {
          value: 0,
          label: '全部',
        },
        {
          value: 1,
          label: '主动',
        },
        {
          value: 2,
          label: '被动',
        }
      ],
      messages:[],
      // 创建编辑框 end
    }
  },
  mounted() {
    if(this.accounts.length){
        this.serviceChange(this.accounts[0]) 
    }   
  },
  computed: {
    ...mapState(['uistate','accountMap','accountListMap','uistate']),
    accounts(){
        const {adminid} = this.uistate
        if( adminid ===-1 || !this.accountListMap[adminid] )return []
        const accounts = this.accountListMap[adminid].map(id=>{
            const item = this.accountMap[id]
            const chars = pinyin.getFullChars(item.nick+item.wxid+item.alias).toLocaleLowerCase()
            return {
                id:item.id,
                csid:item.csid,
                name:item.nick,
                avatar:item.avatar,
                wxid:item.wxid,
                gender:item.gender,
                chars
            }
        })
        return accounts
    },
    createFilterAccounts(){
      const keyword = pinyin.getFullChars(this.createFilterKeyword).toLocaleLowerCase()
      return this.accounts.filter(item=>item.chars.indexOf(keyword)>-1)
    },
    csid(){
      return this.uistate.adminid
    },
    formatedAccounts() {
      if (!this.accounts.trim()) return []
      return this.accounts.split('\n');
    },
    isDiscuss() {
      console.log(this.$route)
      return this.$route.name == 'discuss'
    }
  },
  components: {
    ChooseServiceAccount,
    QuickReplies,
    LayuiSelect,
    UserListItem,
    Friend,
    message,
    messageButtonGroup,
    messageCard
  },
  watch: {
    accounts(newAccounts,oldAccounts){
      if(!this.service.wxid && newAccounts.length){
        this.serviceChange(newAccounts[0]) 
      }
    },
    service(newservice,oldservice){
      if(newservice.wxid !== oldservice.wxid){
        this.requestRecord(newservice)
      }
    }
  },
  methods: {
    createMessage(message){
      this.messages.unshift(message)
    },
    requestRecord(service){
      const { csid,wxid } = service
      const params = {
        csId:csid, wxAccount:wxid
      }
      this.progressListLoading = true
      this.$api.newResponse.get(params)
        .then(data=>{
          this.progressListLoading = false
          this.progressList = data.map(item=>{
            item.service=service
            let _messages = JSON.parse(item.msgcontent)
            let messages
            if(_messages instanceof Array){
              messages = _messages
            }else{
              messages = [_messages]
            }
            item.messages = messages
            item.listType = 'record'
            return item
          })  
        })
        .catch(e=>{
          this.progressListLoading = false
          this.$msg(e)
        })
    },
    serviceChange(service) {
      this.service = service
    },
    selectChange(val) {
      this.sendType = val
    },

    openEditDialog(progress){
      const { addtype,messages,service,wxaccount,csid,id } = progress
      this.openCreateDialog({
        account:service,
        sendType:addtype,
        messages:[...messages],
        id
      })
    },
    openCreateDialog(params){
      this.createDialogAccount = params.account || {}
      this.sendType = params.sendType || 0
      this.messages = params.messages || [] 
      this.createDialogId = params.id || 0
      this.createDialog = true
    },

    createDialogClosed(){
      this.createDialogId = 0
      this.sendType = 0
      this.messages = []
      this.createFilterKeyword = ''
      this.createDialogAccount = {} 
    },
    createAccountChange(e){
      this.createDialogAccount = this.accounts.filter(item=>item.id === e)[0]
    },
    toggleDetailShow(progress, index) {
      this.progress = progress
      this.detailDrawer = !this.detailDrawer
    },
    changeProgressListType(type, index) {
      const progress = this.progressList[index];
      this.$set(this.progressList, index, {
        ...progress,
        listType: type
      })
    },
    editSetting(res) {
      console.log('edit: ', res)
    },
    deleteSetting(res) {
      const { id,csid,wxaccount } = res
      this.$api.newResponse.del({
        id:res.id,
        csId:csid,
        wxAccount:wxaccount
      }).then(rs=>{
        this.progressList = this.progressList.filter(item=>item.id!==res.id)
        this.detailDrawer = false
        this.$msg('删除成功')
      }).catch(e=>console.log(e))
    },
    chooseMessage(message) {
      this.choosenMessage = message[0]
    },
    createResponse() {
      if(!this.createDialogAccount.wxid){
        this.$message({
          type: 'error',
          message: '请选择设置账号!'
        });
        return
      }
      const { csid,wxid } = this.createDialogAccount
      const sendType = this.sendType
      const messages = [...this.messages]
      if(!messages.length){
        this.$message({
          type: 'error',
          message: '请设置应答内容!'
        });
        return
      }
      const params = {
        csid,wxaccount:wxid,msgcontent:JSON.stringify(messages.reverse()),addtype:sendType||0
      }
      this.createSubmitLoading = true
      this.$api.newResponse.insert(params)
        .then(data=>{
          this.createSubmitLoading = false
          data.service = this.createDialogAccount
          data.messages = JSON.parse(data.msgcontent)
          data.responseRecordList = data.responseRecordList||[]
          if(this.service.wxid === this.createDialogAccount.wxid){
            this.progressList.unshift(data)
          }
          this.$message({
            type: 'success',
            message: '设置成功!'
          });
          this.createDialog = false
        })
        .catch(e=>{
          this.createSubmitLoading = false
          this.$msg(e)
        })
    },
    updateResponse() {
      if(!this.createDialogAccount.wxid){
        this.$message({
          type: 'error',
          message: '请选择设置账号!'
        });
        return
      }
      const { csid,wxid } = this.createDialogAccount
      const sendType = this.sendType
      const messages = [...this.messages]
      if(!messages.length){
        this.$message({
          type: 'error',
          message: '请设置应答内容!'
        });
        return
      }
      const params = {
        id:this.createDialogId,
        csid,wxaccount:wxid,msgcontent:JSON.stringify(messages.reverse()),addtype:sendType||0
      }
      this.createSubmitLoading = true
      this.$api.newResponse.update(params)
        .then(data=>{
          this.createSubmitLoading = false
          data.service = this.createDialogAccount
          data.messages = JSON.parse(data.msgcontent)
          data.responseRecordList = data.responseRecordList||[]

          this.progress = {...this.progress,...data};
          this.progressList.forEach((_progress,index)=>{
            if(_progress.id === data.id){
              this.progressList.splice(index,1,data) 
            }
          })
          this.$message({
            type: 'success',
            message: '更新成功!'
          });
          this.createDialog = false
        })
        .catch(e=>{
          this.createSubmitLoading = false
          this.$msg(e)
        })
    }
  }
}
</script>
<style scoped>
.sub-title{
  padding: 10px;
  border-bottom: 1px solid #e4e4e4;
  border-top: 1px solid #e4e4e4
}
.choose-account{
  background-color: #f5f6f7
}
.choose-account-list{
  height: 100%;
  overflow: auto;
  padding: 10px
}
.check-radio{
  display: none
}
.account-item{
  padding: 5px 10px;
  margin: 2px 0;
  border-radius: 5px;
  width: 100%;
  cursor: pointer;
  transition: background-color 300ms ;
  box-sizing: border-box;
}
.account-item:hover{
  background-color: #e8eff7 
}
.account-item.checked{
  background-color: #dae6f6
}

.discuss-detail-container{
  height: 100%;
  background-color: #f5f6f7;
  border-left: 1px solid #ededed;
  overflow: auto;
  box-sizing: border-box;
}
.record-user-item{
  justify-content: space-between ;
  align-items: center;
  padding: 10px;
}
.checkedUsers{
  min-height: 80px;
}

.quick-plane{
    /* height: 100%;
    overflow: auto;
    min-height: 50%; */
    /* padding: 0 10px;
    background: #f1f1f1; */
}
.quick-item{
    padding: 10px 16px;
    background-color: #fff;
    border-radius: 4px;
    border-left: 5px solid #50bfff;
    margin: 5px 0;  
    cursor: pointer; 
    box-shadow: 0px 1px 1px 1px #ddd;
    transition:transform 200ms;
    padding-right: 10px;
}

.ongoing-item{
  background: #fff;
  padding:10px;
  margin: 5px 10px;
  border-radius: 5px;
  box-shadow: 0 0 1px 0px #ccc;
  cursor: pointer;
  align-items: center;

  transition: background-color 300ms ;
  

}
.ongoing-item:hover{
  background: #e8e8e8;
  box-shadow: 0 0 3px 0px #ccc;
}
.progress-head{
  align-items: center;
  width: 200px;
}
.service-avatar{
  width: 40px;
  height:40px;
  border-radius: 3px;
  object-fit: cover;
}
.service-info{
  justify-content: space-around;
  margin-left: 10px;
  overflow: hidden;
}
.progress-detail-info{
  margin-top: 10px;
}
.progress-detail-time{
  font-size: 14px;
  flex:1;
  text-align: right
}
.progress-detail-setting{
  padding-left: 10px
}
>>> .detail-drawer{
  display: flex;
  flex-direction: column;
}
>>> .detail-drawer .el-drawer__body{
  height: 100%;
}
>>> .detail-drawer .el-drawer__header{
  padding: 10px 20px;
  margin: 0;
  border-bottom: 1px solid #f5f6f7
}
.detail-drawer-container{
  padding: 0 20px;
  height: 100%;
  overflow: auto;
}
.detail-drawer-title{
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
}
.detail-drawer-button-group{
  margin-right: 20px;
}
.detail-drawer-button-group .el-button{
  font-size: 20px;
}
</style>
<style scoped>
.create-container{
  height: 500px;
  overflow:auto;
}
.create-item{
  display: flex;
  flex-direction: row;
  align-items: center;
  margin-bottom: 10px;
}
.create-item-title{
  width: 80px;
  flex-shrink: 0;
}
.create-item-content{
  flex:1
}
.create-item-account{
  display: flex;
  flex-direction: row;
  align-items: center;
}
.create-item-account-avatar{
  width: 20px;
  height:20px;
  border-radius: 10px;
  margin-right: 10px;
}
.create-ctrl{
  padding: 10px 20px; 
  text-align: right;
}
</style>